package com.assembly.oauth2.service;


import com.assembly.entities.Resources;
import com.assembly.entities.SystemUser;
import com.assembly.feign.IFeignSystemController;
import com.assembly.oauth2.exception.ValidateCodeException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("customUserDetailsService") // 不一定不要少了
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IFeignSystemController feignSystemController;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 判断用户名是否为空
        if(StringUtils.isEmpty(username)) {
            throw new ValidateCodeException("用户名不能为空");
        }
        // 2. 通过用户名查询数据库中的用户信息
        SystemUser sysUser = feignSystemController.findUserByUsername(username,2);
        if(sysUser == null) {
            throw new ValidateCodeException("用户名或密码错误");
        }
        // 3. 通过用户id去查询数据库的拥有的权限信息
        List<Resources> menuList =
                feignSystemController.findMenuListByUserId(sysUser.getId());
        // 4. 封装权限信息（权限标识符code）
        List<GrantedAuthority> authorities = null;
        if(CollectionUtils.isNotEmpty(menuList)) {
            authorities = new ArrayList<>();
            for(Resources menu: menuList) {
                // 权限标识
                String code = menu.getCode();
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }
        // 5. 构建UserDetails接口的实现类JwtUser对象
        JwtUser jwtUser = new JwtUser( sysUser.getId(), sysUser.getUsername(),sysUser.getAccount(), sysUser.getPassword(),
                sysUser.getFullName(), sysUser.getImageUrl(), sysUser.getMobile(), sysUser.getEmail(),
                sysUser.getIsAccountNonExpired(), sysUser.getIsAccountNonLocked(),
                sysUser.getIsCredentialsNonExpired(), sysUser.getIsEnabled(),"","",
                authorities );

        return jwtUser;
    }
}
